package com.baizhi.cmfz.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import com.baizhi.cmfz.entity.Admin;
import com.baizhi.cmfz.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RequestMapping("/admin")
@Controller
public class AdminController {
    @Autowired
    private AdminService adminService;
    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session,String code) {
       /*
        if(captcha.verify(code.toLowerCase())){
            boolean a= adminService.login(username, password);
            if (a) {
                Admin admin=new Admin();
                session.setAttribute("admin",admin);
                return "menu";
            } else {
                return "redirect:/login.jsp";
            }
        }else {
            return "redirect:/login.jsp";
        }*/
        ICaptcha captcha = (ICaptcha) session.getAttribute("Captcha");
        if (captcha.verify(code.toLowerCase())) {
            //数据封装
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //获取subject
            Subject subject = SecurityUtils.getSubject();
            //调用登录方法
            try {
                subject.login(token);
                Admin admin = new Admin();
                admin.setId(1);
                session.setAttribute("admin", admin);
                return "menu";
            } catch (Exception e) {
                return "redirect:/login.jsp";
            }
        }else {
            return "redirect:/login.jsp";
        }
    }

@RequestMapping("/getCode")
    public void getCode(HttpServletRequest request, HttpServletResponse response, HttpSession session)throws Exception{
        //定义验证码的高和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        //打印到控制台   可省略
        Console.print(lineCaptcha);
        //将验证码放入session中
        session.setAttribute("Captcha",lineCaptcha);
        //响应到浏览器
        lineCaptcha.write(response.getOutputStream());
    }

    @RequestMapping("showPageAdmin")
    @ResponseBody
    public Map showPageAdmin(int page, int limit){
        return adminService.showPageAdmin(page,limit);
    }
}
